﻿/**  
* Users.cs
*
* 功 能： N/A
* 类 名： Users
*
* Ver    变更日期             负责人  变更内容
* ───────────────────────────────────
* V0.01  2014/6/29/星期日 21:25:34   N/A    初版
*
* Copyright (c) 2014  Spring Story  Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│　此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．　│
*│　版权所有： Spring Story 有限公司　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using eTruck.IDAL;
using eTruck.DBUtility;
using eTruck.Common;

namespace eTruck.SQLServerDAL
{
	/// <summary>
	/// 数据访问类:Users
	/// </summary>
	public partial class Users:IUsers
	{
		public Users()
		{}
		#region  BasicMethod

		/// <summary>
		/// 得到最大ID
		/// </summary>
		public int GetMaxId()
		{
		return DbHelperSQL.GetMaxID("UserID", "Users"); 
		}

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(string UserName)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from Users");
            strSql.Append(" where UserName=@UserName ");
			SqlParameter[] parameters = {
					new SqlParameter("@UserName", SqlDbType.VarChar)			
                                        };
            parameters[0].Value = UserName;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public bool Add(eTruck.Model.Users model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into Users(");
			strSql.Append("UserID,UserName,FirstName,LastName,EmailAddress,Phone,DepartMent,LastUpdated,Password)");
            strSql.Append(" select isnull(max(UserID),0)+1");
            strSql.Append(",@UserName,@FirstName,@LastName,@EmailAddress,@Phone,@DepartMent,getdate(),@Password from Users");
			SqlParameter[] parameters = {
					new SqlParameter("@UserName", SqlDbType.VarChar,20),
					new SqlParameter("@FirstName", SqlDbType.VarChar,20),
					new SqlParameter("@LastName", SqlDbType.VarChar,20),
					new SqlParameter("@EmailAddress", SqlDbType.VarChar,50),
					new SqlParameter("@Phone", SqlDbType.VarChar,20),
					new SqlParameter("@DepartMent", SqlDbType.VarChar,20),
					new SqlParameter("@Password", SqlDbType.NVarChar,32)};
			parameters[0].Value = model.UserName;
			parameters[1].Value = model.FirstName;
			parameters[2].Value = model.LastName;
			parameters[3].Value = model.EmailAddress;
			parameters[4].Value = model.Phone;
			parameters[5].Value = model.DepartMent;
            parameters[6].Value =Encrypt.MD5Encrypt(model.Password);

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(eTruck.Model.Users model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update Users set ");
			strSql.Append("UserName=@UserName,");
			strSql.Append("FirstName=@FirstName,");
			strSql.Append("LastName=@LastName,");
			strSql.Append("EmailAddress=@EmailAddress,");
			strSql.Append("Phone=@Phone,");
			strSql.Append("DepartMent=@DepartMent,");
			strSql.Append("LastUpdated=getdate()");
			strSql.Append(" where UserID=@UserID ");
			SqlParameter[] parameters = {
					new SqlParameter("@UserName", SqlDbType.VarChar,20),
					new SqlParameter("@FirstName", SqlDbType.VarChar,20),
					new SqlParameter("@LastName", SqlDbType.VarChar,20),
					new SqlParameter("@EmailAddress", SqlDbType.VarChar,50),
					new SqlParameter("@Phone", SqlDbType.VarChar,20),
					new SqlParameter("@DepartMent", SqlDbType.VarChar,20),
					new SqlParameter("@UserID", SqlDbType.Int,4)};
			parameters[0].Value = model.UserName;
			parameters[1].Value = model.FirstName;
			parameters[2].Value = model.LastName;
			parameters[3].Value = model.EmailAddress;
			parameters[4].Value = model.Phone;
			parameters[5].Value = model.DepartMent;
			parameters[6].Value = model.UserID;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int UserID)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Users ");
			strSql.Append(" where UserID=@UserID ");
			SqlParameter[] parameters = {
					new SqlParameter("@UserID", SqlDbType.Int,4)			};
			parameters[0].Value = UserID;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string UserIDlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Users ");
			strSql.Append(" where UserID in ("+UserIDlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public eTruck.Model.Users GetModel(int UserID)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 UserID,UserName,FirstName,LastName,EmailAddress,Phone,DepartMent,LastUpdated from Users ");
			strSql.Append(" where UserID=@UserID ");
			SqlParameter[] parameters = {
					new SqlParameter("@UserID", SqlDbType.Int,4)			};
			parameters[0].Value = UserID;

			eTruck.Model.Users model=new eTruck.Model.Users();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public eTruck.Model.Users DataRowToModel(DataRow row)
		{
			eTruck.Model.Users model=new eTruck.Model.Users();
			if (row != null)
			{
				if(row["UserID"]!=null && row["UserID"].ToString()!="")
				{
					model.UserID=int.Parse(row["UserID"].ToString());
				}
				if(row["UserName"]!=null)
				{
					model.UserName=row["UserName"].ToString();
				}
				if(row["FirstName"]!=null)
				{
					model.FirstName=row["FirstName"].ToString();
				}
				if(row["LastName"]!=null)
				{
					model.LastName=row["LastName"].ToString();
				}
				if(row["EmailAddress"]!=null)
				{
					model.EmailAddress=row["EmailAddress"].ToString();
				}
				if(row["Phone"]!=null)
				{
					model.Phone=row["Phone"].ToString();
				}
				if(row["DepartMent"]!=null)
				{
					model.DepartMent=row["DepartMent"].ToString();
				}
				if(row["LastUpdated"]!=null && row["LastUpdated"].ToString()!="")
				{
					model.LastUpdated=DateTime.Parse(row["LastUpdated"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select UserID,UserName,FirstName,LastName,EmailAddress,Phone,DepartMent,LastUpdated ");
			strSql.Append(" FROM Users ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" UserID,UserName,FirstName,LastName,EmailAddress,Phone,DepartMent,LastUpdated ");
			strSql.Append(" FROM Users ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM Users ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.UserID desc");
			}
			strSql.Append(")AS Row, T.*  from Users T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "Users";
			parameters[1].Value = "UserID";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod
        ///<summary>
        ///验证账户
        /// </summary>
        /// <returns>返回userid,如果返回为-1，则验证失败</returns>
        public int Login(string UserName, string Pwd)
        {
            int UserID = -1;
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select UserID from Users ");
            strSql.Append(" where UserName=@UserName and Password=@Password ");
            SqlParameter[] parameters = {
					new SqlParameter("@UserName", SqlDbType.VarChar,20),
					new SqlParameter("@Password", SqlDbType.NVarChar,32)				
                                        };
            parameters[0].Value = UserName;
            parameters[1].Value =Encrypt.MD5Encrypt(Pwd);
            //parameters[1].Value = Pwd;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
            if (obj == null)
            {
                UserID =-1;
            }
            else
            {
                try
                {
                    UserID = Convert.ToInt32(obj);
                }
                catch
                {
                    UserID = -1;
                }
            }
            return UserID;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns>修改成功返回空值，否则返回对应错误数值！</returns>
        public string UpdatePassword(int UserID,string oldpwd,string newpwd)
        {
            string result = "";
            //check if the old pwd is correct!
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select UserID from Users ");
            strSql.Append(" where UserID=@UserID and Password=@Password ");
            SqlParameter[] Parms = {
					new SqlParameter("@Password", SqlDbType.NVarChar,32),
					new SqlParameter("@UserID", SqlDbType.Int,4)};
            Parms[0].Value = Encrypt.MD5Encrypt(oldpwd);
            Parms[1].Value = UserID;

            if (DbHelperSQL.Exists(strSql.ToString(),Parms))
            {
                //begin to update password
                strSql.Clear();
                strSql.Append("update Users set ");
                strSql.Append(" Password=@Password,");
                strSql.Append(" LastUpdated=getdate()");
                strSql.Append(" where UserID=@UserID ");
                SqlParameter[] parameters = {
					new SqlParameter("@Password", SqlDbType.NVarChar,32),
					new SqlParameter("@UserID", SqlDbType.Int,4)};
                parameters[0].Value = Encrypt.MD5Encrypt(newpwd);
                parameters[1].Value = UserID;

                int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                if (rows > 0)
                {
                    result = "";
                }
                else
                {
                    result = "更新密码失败，请重试！";
                }
            }
            else
            {
                result = "对不起，原始密码错误！";
            }
            return result;
        }
        
		#endregion  ExtensionMethod
	}
}

